﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace _使用参数化执行SQL语句
{
    public class DataTableToListUtil
    {
        /// <summary>
        /// 将DataTable转换为List类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static IList<T> ConvertToListByTable<T>(DataTable dt) where T : class
        {
            List<DataRow> dataRows = new List<DataRow>();
            foreach (DataRow item in dt.Rows)
            {
                dataRows.Add(item);
            }
            return ConvertToList<T>(dataRows);
        }

        /// <summary>
        /// 将所有dataRow转换为List 
        /// </summary>
        /// <typeparam name="T">泛型T</typeparam>
        /// <param name="dataRows">所有dataTable的Row</param>
        /// <returns>转换完成的List集合</returns>
        private static IList<T> ConvertToList<T>(List<DataRow> dataRows) where T : class
        {
            IList<T> data = null;
            if (dataRows != null)
            {
                data = new List<T>();
                foreach (DataRow dr in dataRows)
                {
                    T item = ConvertToEntity<T>(dr);
                    data.Add(item);
                }
            }
            return data;
        }

        /// <summary>
        /// 将单个dataRow转换为泛型T
        /// </summary>
        /// <typeparam name="T">泛型T</typeparam>
        /// <param name="dr">单个DataRow</param>
        /// <returns>转换完成的泛型T</returns>
        private static T ConvertToEntity<T>(DataRow dr)
        {
            T obj = default(T);
            if (dr != null)
            {

                #region 泛型不能new时,声明变量
                //当引用类型无法new时，使用这样的方法来声明变量
                //T obj = default(T);
                //obj = Activator.CreateInstance<T>(); 
                #endregion

                obj = Activator.CreateInstance<T>();
                foreach (DataColumn dc in dr.Table.Columns)
                {
                    PropertyInfo propertyInfo = obj.GetType().GetProperty(dc.ColumnName);
                    try
                    {
                        object value = dr[dc.ColumnName];
                        propertyInfo.SetValue(obj, value, null);

                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
            }
            return obj;
        }
    }
}
